$(function () {
  // 高层建筑 添加页面 打开
  $("#addbuildingListBtn").on("click", function (e) {
    e.preventDefault();
    $(".building-pop").addClass("is-visible3");
    $('#buildingForm select').find("option:first").prop("selected", "selected");
    // 获取所属组织
    $.ajax({
      url: '/organization/list?type=street',
      success: function (res) {
        console.log(res)
        $('#buildingForm .organization').html('');
        for (var i = 0; i < res.data.length; i++) {
          $('#buildingForm .organization').append('<option value="' + res.data[i].id + '" selected>' + res.data[i].orgName + '</option>');
        }
      },
      error: function (res) {
        console.log(res);
      }
    });

    // 给隐藏域重新赋值
    $("#buildingForm .buildingFormHidden").val('1');
  })

  // 高层建筑 添加页面 关闭
  $(".building-pop").on("click", function (event) {
    if (
      $(event.target).is(".cd-popup-close1") ||
      $(event.target).is(".building-pop") || $(event.target).is(".cd-popup-close")
    ) {
      event.preventDefault();
      $(this).removeClass("is-visible3");
      //Modal验证销毁重构
      $("#buildingForm").data('bootstrapValidator').destroy();
      $('#buildingForm').data('bootstrapValidator', null);
      $('#buildingForm input').val('');
      $('#buildingForm option:first').prop("selected", "selected");
      // 清除照片
      multipartFile = {};
      $('#buildingForm .pic').attr('src', '');
      $("#buildingForm .pic").css("opacity", 0);
      $('#buildingForm .pic').removeClass('opacity1');
      $("#buildingForm").find(".buildingImg").addClass("bac");
      addBuildingFormValidator();
    }
  });
  // 高层建筑 添加页面
  // 高层建筑 添加页面 点击上传相片
  var picThat;
  var multipartFile;
  var file;
  var imgUpload = 0;
  $("#buildingForm .buildingImg").on("click", '.pic', function () {
    console.log(this);
    var $this = $(this);
    $(this).parent().find(".upload").click(); //隐藏了input:file样式后，点击头像就可以本地上传
    // var $this = $(this).parent().find(".upload");
    $(this).parent().find(".upload").on("change", function (e) {
      imgUpload++;
      console.log(this.files[0]);
      var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
      console.log(objUrl);
      picThat = this;
      console.log(this);
      if (objUrl) {
        $this.parent().removeClass("bac");
        $this.parent().find(".pic").css("opacity", 1);
        $this.parent().find(".pic").attr("src", objUrl);
        $this.parent().find(".pic").addClass('opacity1');
      } else {
        $this.parent().find(".pic").removeClass('opacity1');
      }
    });
  });

  function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) { // basic
      url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
      url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
      url = window.webkitURL.createObjectURL(file);
    }
    return url;
  }

  // 高层建筑 添加页面的 删除头像
  $("#buildingForm .buildingImg .del").on("click", function () {
    $(this).siblings('.pic').attr('src', '');
    multipartFile = {};
    $(this).siblings('.pic').removeClass('opacity1');
    $("#buildingForm .pic").css("opacity", 0);
    $("#buildingForm").find(".buildingImg").addClass("bac");
  })

  // 高层建筑 添加  验证form表单
  addBuildingFormValidator();

  function addBuildingFormValidator() {
    $("#buildingForm").bootstrapValidator({
      message: 'This value is not valid',
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      fields: {
        // linkMain1: {
        //     validators: {
        //         notEmpty: {
        //             message: '负责人不能为空'
        //         },
        //     }
        // },
        // linkPhone1: {
        //     validators: {
        //         notEmpty: {
        //             message: '电话不能为空'
        //         }
        //     }
        // },
        // deviceName: {
        //     validators: {
        //         notEmpty: {
        //             message: '单位名称不能为空'
        //         }
        //     }
        // },
        // address: {
        //     validators: {
        //         notEmpty: {
        //             message: '地址不能为空'
        //         }
        //     }
        // },
        // latitude: {
        //     validators: {
        //         notEmpty: {
        //             message: '经度不能为空'
        //         }
        //     }
        // },
        // longitude: {
        //     validators: {
        //         notEmpty: {
        //             message: '纬度不能为空'
        //         }
        //     }
        // }
      }
    }).on("success.form.bv", function (e) {
      e.preventDefault();
      var $form = $(e.target);
      console.log($form.serialize());
      // console.log($form.serialize());
      var obj = new FormData($form[0]);
      // var obj = $form.serialize();
      console.log(obj);
      // 获取orgId 
      var orgId = $("#buildingForm .organization").val();
      console.log(orgId);
      $.ajax({
        url: '/hightBuilding/save?orgId=' + orgId,
        type: 'POST',
        async: false,
        data: obj,
        contentType: false,
        processData: false,
        success: function (result) {
          console.log(result);
          if (result.status == 200) {
            $('.building-pop').removeClass('is-visible3');
            tipModalFunc('添加成功!');
            // 添加成功后重新渲染
            buildingListPageList(buildingListPageNumCurr);
            // 清除照片
            obj = {};
            $('#buildingForm .pic').attr('src', '');
            $("#buildingForm .pic").css("opacity", 0);
            $('#buildingForm .pic').removeClass('opacity1');
            $("#buildingForm").find(".buildingImg").addClass("bac");
            //Modal验证销毁重构
            $("#buildingForm").data('bootstrapValidator').destroy();
            $('#buildingForm').data('bootstrapValidator', null);
            $('#buildingForm input').val('');
            $('#buildingForm select').find("option:first").prop("selected", "selected");
            addBuildingFormValidator();
          } else {
            console.log(result.message);
            addBuildingFormValidator();
          }
        }
      });
    });
  }

  // 建筑详情页面 打开
  // $(".buildingDetail-pop").addClass('is-visible3');
  // 建筑详情页面 关闭
  $(".buildingDetail-pop").on("click", function (event) {
    if (
      $(event.target).is(".cd-popup-close1") ||
      $(event.target).is(".buildingDetail-pop") || $(event.target).is(".cd-popup-close")
    ) {
      event.preventDefault();
      $(this).removeClass("is-visible3");
      console.log(this);
    }
    console.log(this);
  });
  // 建筑列表页面 关闭
  $(".buildingList-pop").on("click", function (event) {
    if (
      $(event.target).is(".cd-popup-close1") ||
      $(event.target).is(".buildingList-pop") || $(event.target).is(".cd-popup-close")
    ) {
      event.preventDefault();
      $(this).removeClass("is-visible3");
    }
  });
  // 建筑列表展示 页面 打开
  var n;
  $('.buildingList-target').on('click', function () {
    $(".buildingList-pop").addClass('is-visible3');
    $('.bgBox').hide();
    pageMenuOff = true;
    n = 1;
    buildingListPageList(n);
    // 清除全选按钮的选择状态
    $('#buildingListSelectAll').prop('checked', false);
  });

  // 建筑列表展示 页面 分页
  var buildingListPageNum = 1;
  var buildingListPageNumCurr = 1;

  function buildingListPageFunc(pageSum, startPageNum) {
    console.log(pageSum);
    if (pageSum <= 1) {
      $('#buildingListPageBox .pageJump').hide()
    } else {
      $('#buildingListPageBox .pageJump').show()
    }
    Page({
      num: pageSum, //页码数
      startnum: startPageNum, //指定页码
      elem: $('#buildingListPage'), //指定的元素
      callback: function (n) { //回调函数
        console.log(n)
        buildingListPageNumCurr = n;
        buildingListPageList(n);
        // 当翻到下一页时 清除掉 全选按钮的 选中状态
        $("#buildingListSelectAll").prop("checked", false);
      }
    });
  };

  // 渲染 建筑列表
  function buildingListPageList(n) {
    var orgId = localStorage.getItem('userOrgId');
    $.ajax({
      // http://localhost:9092/hightBuilding/getList/likeBuildingName?type=1&buildingName=小明&size=1&page=0
      url: '/hightBuilding/getList/likeBuildingName?type=1&size=8&page=' + (n - 1),
      type: 'GET',
      async: false,
      success: function (result) {
        console.log(result);
        var content = result.data.content;
        console.log(content);
        buildingListPageNum = result.data.totalPages;
        size = result.data.size;
        $('#buildingListModal .tbodyList').html('');
        for (var i = 0; i < content.length; i++) {
          $('#buildingListModal .tbodyList').append('<tr><td><input type="checkbox" class="check" devid="' + content[i].id + '"></td><td>' + ((n - 1) * size + i + 1) + '</td><td>' + content[i].buildingType + '</td><td>' + content[i].buildingName + '</td><td>' + content[i].address + '</td><td>' + content[i].linkMain1 + '</td><td>' + content[i].linkPhone1 + '</td><td>' + content[i].organization.orgName + '</td><td><span class="seeDetailsStyle">详情</span></td></tr>');
        }
        buildingListPageFunc(buildingListPageNum, n);
      }
    });
  }
  // 全选 反选
  $("#buildingListSelectAll").on("click", function () {
    var allcheck = $("#buildingListSelectAll").prop("checked");
    $("#buildingListModal .tbodyList .check").prop("checked", allcheck);
  });
  // 反选
  $("#buildingListModal .tbodyList").on("click", '.check', function () {
    var length1 = $("#buildingListModal .tbodyList").find(":checkbox").length;
    var length2 = $("#buildingListModal .tbodyList").find(":checked").length;
    if (length1 == length2) {
      $("#buildingListSelectAll").prop("checked", true);
    } else {
      $("#buildingListSelectAll").prop("checked", false);
    }
  });

  // 批量 删除
  $("#delbuildingListBtn").on("click", function (e) {
    e.preventDefault();
    if ($('#buildingListSelectAll').prop("checked")) {
      buildingListPageNumCurr = buildingListPageNumCurr - 1;
    }
    delTipModalFunc('确认删除？');
    // 点击 确定
    $("#delTipModal .delCoonfirmTipConfirm").on("click", function (event) {
      event.preventDefault();
      $("#buildingListModal .tbodyList").find(":checked").each(function (index, ele) {
        var devid = $(this).attr("devid");
        $.ajax({
          url: '/hightBuilding/delete/' + devid,
          type: 'post',
          data: {
            _method: "DELETE"
          },
          dataTpe: "json",
          success: function (res) {
            console.log(res);
            $('#buildingListSelectAll').prop("checked", false);
            $(".delTipModal").removeClass("is-visible3");
            tipModalFunc('删除成功');
            buildingListPageList(buildingListPageNumCurr);
          },
          error: function (res) {
            console.log(res);
          }
        });
      });
    })
    // 点击 取消 
    $("#delTipModal .delCoonfirmTipCancel").on("click", function (event) {
      event.preventDefault();
      $(".delTipModal").removeClass("is-visible3");
      $("#buildingListModal .tbodyList").find(":checked").each(function (index, ele) {
        $('#buildingListSelectAll').prop("checked", false);
        $(this).prop("checked", false);
      });
    })
  });
});